package com.bcu.cn.onlineexamsystem.exammanage.service.impl;

import com.bcu.cn.onlineexamsystem.exammanage.entity.Exam;
import com.bcu.cn.onlineexamsystem.exammanage.entity.ExamForm;
import com.bcu.cn.onlineexamsystem.exammanage.entity.Question;
import com.bcu.cn.onlineexamsystem.exammanage.entity.StudentExam;
import com.bcu.cn.onlineexamsystem.exammanage.mapper.ExamMapper;
import com.bcu.cn.onlineexamsystem.exammanage.service.ExamService;
import com.bcu.cn.onlineexamsystem.exammanage.service.StudentExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ExamServiceImpl implements ExamService {
    private static final Logger logger = LoggerFactory.getLogger(ExamServiceImpl.class);

    @Autowired
    private ExamMapper examMapper;
    
    @Autowired
    private StudentExamService studentExamService;

    @Override
    public List<Exam> getExamsByTeacherId(String teacherId) {
        logger.info("开始查询教师[{}]的考试列表", teacherId);
        
        // 先测试数据库连接
        int totalExams = examMapper.countExams();
        logger.info("数据库中总共有{}场考试", totalExams);
        
        List<Exam> exams = examMapper.findByTeacherId(teacherId);
        logger.info("查询到教师[{}]的考试数量: {}", teacherId, exams.size());
        
        return exams;
    }

    @Override
    @Transactional
    public Integer createExam(ExamForm examForm, String teacherId) {
        // 1. 创建考试基本信息
        Exam exam = new Exam();
        exam.setExamName(examForm.getExamName());
        exam.setExamType(examForm.getExamType());
        exam.setStartTime(examForm.getStartTime());
        exam.setEndTime(examForm.getEndTime());
        exam.setDuration(examForm.getDuration());
        exam.setCourseId(examForm.getCourseId());
        exam.setTotalScore(examForm.getTotalScore());
        exam.setTeacherId(teacherId);
        exam.setStatus(0); // 0表示未开始
        
        // 2. 保存考试信息
        examMapper.insertExam(exam);
        Long examId = exam.getExamId();
        
        // 3. 保存考试班级关联
        for (Long classId : examForm.getClassIds()) {
            examMapper.insertExamClass(examId, classId);
        }
        
        // 4. 保存考试题目关联
        for (Long questionId : examForm.getQuestionIds()) {
            examMapper.insertExamQuestion(examId, questionId, 0); // 0表示默认顺序
        }
        
        return examId.intValue();
    }

    @Override
    @Transactional
    public boolean deleteExam(String examId) {
        try {
            // 删除考试
            int result = examMapper.deleteExam(examId);
            return result > 0;
        } catch (Exception e) {
            logger.error("删除考试失败", e);
            throw new RuntimeException("删除考试失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public boolean publishExam(String examId) {
        try {
            // 1. 获取考试信息
            Exam exam = examMapper.getExamDetail(examId);
            if (exam == null) {
                logger.error("考试不存在: {}", examId);
                return false;
            }
            
            // 2. 更新考试状态为1（进行中）
            int result = examMapper.updateExamStatus(examId, 1);
            if (result > 0) {
                // 3. 创建学生考试记录
                studentExamService.createStudentExamRecords(Long.parseLong(examId), exam.getCourseId());
                return true;
            }
            return false;
        } catch (Exception e) {
            logger.error("发布考试失败", e);
            throw new RuntimeException("发布考试失败：" + e.getMessage());
        }
    }

    @Override
    public Map<String, Object> getExamDetail(String examId) {
        try {
            Map<String, Object> detail = new HashMap<>();
            
            // 获取考试基本信息
            Exam exam = examMapper.getExamDetail(examId);
            detail.put("exam", exam);
            
            // 获取考试题目
            List<Question> questions = examMapper.getExamQuestions(examId);
            detail.put("questions", questions);
            
            // 获取考试记录
            List<StudentExam> records = examMapper.getExamRecords(examId);
            detail.put("records", records);
            
            return detail;
        } catch (Exception e) {
            logger.error("获取考试详情失败", e);
            throw new RuntimeException("获取考试详情失败：" + e.getMessage());
        }
    }

    @Override
    public void autoEndExpiredExams() {
        int count = examMapper.endAllExpiredExams();
        if (count > 0) {
            logger.info("自动将{}场考试状态设置为已结束", count);
        }
    }

    @Override
    public Map<String, Object> getExamQuestionStat(String examId) {
        List<Map<String, Object>> statList = examMapper.getExamQuestionStat(examId);
        ObjectMapper objectMapper = new ObjectMapper();
        for (Map<String, Object> q : statList) {
            if (q.get("type") != null && "choice".equals(q.get("type"))) {
                Object optionStats = q.get("optionStats");
                if (optionStats instanceof String && ((String) optionStats).startsWith("[")) {
                    try {
                        List<Integer> stats = objectMapper.readValue((String) optionStats, new TypeReference<List<Integer>>(){});
                        q.put("optionStats", stats);
                    } catch (Exception e) {
                        q.put("optionStats", new int[]{});
                    }
                } else {
                    q.put("optionStats", new int[]{});
                }
            }
        }
        Map<String, Object> result = new HashMap<>();
        result.put("questions", statList);
        return result;
    }
} 